package com.example.everying.service.user.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.example.everying.constant.OrderConstants;
import com.example.everying.constant.ResultCodeEnum;
import com.example.everying.mapper.user.UserBalanceMapper;
import com.example.everying.mapper.user.UserBalanceTransactionMapper;
import com.example.everying.model.dto.user.UserPageDto;
import com.example.everying.model.entity.user.UserBalanceEntity;
import com.example.everying.model.entity.user.UserBalanceTransactionEntity;
import com.example.everying.model.entity.user.UserEntity;
import com.example.everying.service.user.UserBalanceService;
import com.example.everying.utils.AmtUtils;
import com.example.everying.utils.CampusException;
import com.example.everying.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
public class UserBalanceServiceImpl extends ServiceImpl<UserBalanceMapper, UserBalanceEntity> implements UserBalanceService {
    @Autowired
    private UserBalanceTransactionMapper txMapper;
    @Transactional
    public UserBalanceEntity getBalanceByUserId(String userId) {
        return query().eq("user_id", userId).one();
    }

    /**
     * @param userId
     * @param amount
     * @return
     */
    @Override
    public boolean deductBalance(String userId, BigDecimal amount) {
        boolean success = baseMapper.mpDeductBalance(userId, amount);
        if (!success) {
            throw new CampusException("扣款失败",201);
        }
        return true;
    }

    /**
     * @param userId
     * @param amount
     * @return
     */
    @Override
    public boolean addBalance(String userId, BigDecimal amount) {
////         幂等性检查
//        if (txMapper.exists(
//                new LambdaQueryWrapper<UserBalanceTransactionEntity>()
//                        .eq(UserBalanceTransactionEntity::getTxId, bizId))) {
//            throw new CampusException( ResultCodeEnum.ORDER_ALREADY_PROCESSED);
//        }
        boolean success = baseMapper.mpAddBalance(userId, amount);
        if (!success) {
            throw new CampusException("增加失败：数据已变更",201);
        }
        return true;
    }




}

